import time
import random
import hashlib
import requests

from data.model.Trade import RET
from broker.tws.constant.Constant import RetCode

import logging
log = logging.getLogger("syslog")

class HttpsClient:

    def __init__(self, server_url: str):
        """
        Create the request client instance.
        """
        self.server_url = server_url

    def get(self, uri: str, params: dict = None, data=None):
        headers = self._generate_header()
        reqUrl = "%s%s" % (self.server_url, uri)

        log.debug("GET\t%s\t%s\t%s" % (reqUrl, params, data))
        respR = requests.get(reqUrl, params=params, data=data, headers=headers, verify=False)
        ret = RET(respR.status_code)
        if respR.status_code == RetCode.OK:
            log.debug("%s 请求返回：%s" % (uri, respR.text))
            ret_data = respR.json()
            if isinstance(ret_data, dict) and "error" in ret_data and ret_data["error"]:
                ret.error(msg=ret_data["error"])
                return ret, None
            return ret, ret_data
        else:
            if respR.status_code == RetCode.EXCEPTION:
                ret.msg = respR.text
            log.error("%s 请求返回异常错误：%s %s" % (uri, respR.status_code, respR.text))
            return ret, None

    def post(self, uri: str, params=None, data=None):
        headers = self._generate_header()
        reqUrl = "%s%s" % (self.server_url, uri)
        log.debug("POST\t%s\t%s\t%s" % (reqUrl, params, data))
        respR = requests.post(reqUrl, params=params, json=data, headers=headers, verify=False)
        ret = RET(respR.status_code)
        if respR.status_code == RetCode.OK:
            log.debug("%s 请求返回：%s" % (uri, respR.text))
            ret_data = respR.json()
            if isinstance(ret_data, dict) and "error" in ret_data and ret_data["error"]:
                ret.error(msg=ret_data["error"])
                return ret, None
            return ret, ret_data
        else:
            if respR.status_code == RetCode.EXCEPTION:
                ret.msg = respR.text
            log.error("%s 请求返回异常错误：%s %s" % (uri, respR.status_code, respR.text))
            return ret, None

    def _generate_header(self) -> dict:
        """
        生成请求头
        """
        return {
            'Connection': 'close',
            'Content-Type': 'application/json'
        }
